package cn.sytton.taffe.auth.service.impl;

import cn.sytton.taffe.auth.entity.LoginEntity;
import cn.sytton.taffe.auth.service.ILoginService;
import cn.sytton.taffe.framework.captcha.CaptchaFactory;
import cn.sytton.taffe.framework.security.entity.LoginUser;
import cn.sytton.taffe.framework.security.jwt.JwtFactory;
import cn.sytton.taffe.framework.security.sms.SmsCodeAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 登录服务层实现类
 *
 * @author skyrock
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginService implements ILoginService {

    @Resource
    private CaptchaFactory captchaFactory;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private JwtFactory jwtFactory;

    @Override
    public String loginByPwd(LoginEntity loginEntity) {
        if (!captchaFactory.verifyCode(loginEntity.getCaptchaId(), loginEntity.getCaptchaCode())) {
            throw new BadCredentialsException("图片验证码错误或已过期");
        }
        Authentication authentication =  authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginEntity.getLoginName(), loginEntity.getPassword())
        );
        return generateToken(authentication);
    }

    @Override
    public String loginBySms(LoginEntity loginEntity) {

        Authentication authentication =  authenticationManager.authenticate(
                new SmsCodeAuthenticationToken(loginEntity.getCellphone(), loginEntity.getSmsCode())
        );
        return generateToken(authentication);
    }

    @Override
    public String generateToken(Authentication authentication) {
        //存储认证信息
        //SecurityContextHolder.getContext().setAuthentication(authentication);

        final LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //生成token
        return jwtFactory.createToken(loginUser);
    }
}
